package com.hangup.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import com.devil.bbsclient.R;
import com.hangup.net.ActivityKeys;
import com.hangup.net.HttpUtil;
import com.hangup.pojo.Post;
import com.hangup.pojo.Student;
import com.hangup.util.JsonUtil;
import com.hangup.util.NetWorkUtil;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class BBSActivity extends Activity {
	private Button rbt;
	private Button lbt;

	private String url;
	private Dialog dialog;
	private String result;

	ListView listV;
	ArrayList<Post> post_;
	ArrayList<Student> stu_;
	PublicApplication pa;

	Handler handler_ = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0:
				Toast.makeText(BBSActivity.this, R.string.net,
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				dialog = NetWorkUtil.showDialog(BBSActivity.this, null,
						"BBS论坛", "帖子加载中,请稍等");
				dialog.show();
				break;
			case 2:
				dialog.cancel();
				Toast.makeText(BBSActivity.this, "连接服务器异常!", Toast.LENGTH_LONG)
						.show();
				break;
			case 3:
				listV = (ListView) findViewById(R.id.post_list);
				SimpleAdapter adapter = new SimpleAdapter(BBSActivity.this,
						getData(post_, stu_), R.layout.list_item, new String[] {
								"nick", "time", "theme", "count" }, new int[] {
								R.id.post_nick, R.id.post_time,
								R.id.post_theme, R.id.post_count });
				listV.setAdapter(adapter);
				listV.setOnItemClickListener(new itemClick());
				dialog.cancel();
				break;
			case 4:
				dialog.cancel();
				Toast.makeText(BBSActivity.this, "帖子加载失败...",
						Toast.LENGTH_SHORT).show();
				break;
			case 5:
				dialog.cancel();
				Toast.makeText(BBSActivity.this, "还没有帖子哦,赶紧比发表吧!",
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bbs);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		rbt = (Button) findViewById(R.id.btRefresh);
		rbt.setOnClickListener(new refresh());
		lbt = (Button) findViewById(R.id.btLogin);
		lbt.setOnClickListener(new login());

		if (((PublicApplication) getApplicationContext()).isLogin_flag()) {// 登录过之后改变button
			lbt.setVisibility(View.GONE);
			Button tbt = (Button) findViewById(R.id.btTopic);
			tbt.setVisibility(View.VISIBLE);
			tbt.setOnClickListener(new topic());
		}
		SysApplication.getInstance().addActivity(this);

		if (NetWorkUtil.NetType(BBSActivity.this) == null) {
			handler_.sendMessage(handler_.obtainMessage(0));
			return;
		}

		postLists();
		pa = (PublicApplication) getApplication();

	}

	private final class refresh implements OnClickListener {

		@Override
		public void onClick(View v) {
			// Intent intent = new Intent();
			// intent.setClass(BBSActivity.this, MainActivity.class);
			// startActivity(intent);
			postLists();
		}
	}

	private final class login implements OnClickListener {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(BBSActivity.this, LoginActivity.class);
			startActivity(intent);

		}
	}

	private final class topic implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(BBSActivity.this, TopicActivity.class);
			startActivity(intent);
		}
	}

	public void postLists() {
		url = ActivityKeys.BASE_URL + ActivityKeys.POST_LIST_URL;
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler_.sendMessage(handler_.obtainMessage(1));
				if (!NetWorkUtil.webServer()) {
					handler_.sendMessage(handler_.obtainMessage(2));
					return;
				}
				result = HttpUtil.getHttpPostResultForUrl(url);
				if (result == null) {
					handler_.sendMessage(handler_.obtainMessage(4));
				} else if (result.equals("null")) {
					handler_.sendMessage(handler_.obtainMessage(5));
				} else {
					int index = result.indexOf("][") + 1;
					String post_json = result.substring(0, index);
					String stu_json = result.substring(index);
					post_ = JsonUtil.parseList(post_json, Post[].class);
					stu_ = JsonUtil.parseList(stu_json, Student[].class);
					pa.setPost_(post_);
					pa.setStus_(stu_);
					handler_.sendMessage(handler_.obtainMessage(3));
				}
			}
		}).start();
	}

	private ArrayList<HashMap<String, Object>> getData(ArrayList<Post> posts,
			ArrayList<Student> stus) {
		Collections.reverse(posts);
		ArrayList<HashMap<String, Object>> dlist = new ArrayList<HashMap<String, Object>>();
		if (posts.size() > 0) {
			for (Post post : posts) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				for (Student stu : stus) {
					if (stu.getStu_id() == post.getStu_id()) {
						map.put("nick", "楼主:" + stu.getStu_nick());
						break;
					}
				}
				map.put("time", post.getTime());
				map.put("theme", post.getTheme());
				map.put("count", post.getCount() + "次回复");
				dlist.add(map);
			}
		}
		return dlist;
	}

	private final class itemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// TODO Auto-generated method stub
			pa.setPost_index(position);
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			int stuId = post_.get(position).getStu_id();
			for (Student stu : stu_) {
				if (stu.getStu_id() == stuId) {
					bundle.putString("nick", stu.getStu_nick());
					bundle.putInt("post_id", post_.get(position).getPost_id());
					break;
				}
			}
			intent.putExtras(bundle);
			intent.setClass(BBSActivity.this, TopicInfoActivity.class);
			startActivity(intent);
		}
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		postLists();
	}

}
